#!/usr/bin/env python
# -*- coding: utf-8 -*-
# title       :
# author      : jarry
import os
# add license check
# import THLicense.CheckLicense as cl
# cl.CheckLicense()

# from .widget.InitQtModule import *
from Qt.QtCore import *
from Qt.QtGui import *
from Qt.QtWidgets import *

from JTK.jcore.JFile.JJson import JJson

from .widget import AOVActiveItemWidget, AOVAvailableWidget, AOVLightGroupWidget

# reload(AOVActiveItemWidget)
# reload(AOVAvailableWidget)
# reload(AOVLightGroupWidget)
# import data.dict2json as d2j
# import jarryLibs.RenderQss as rq
from .widget import QColorScheme as qcs

# reload(qcs)
try:
    import maya.cmds as cmds
    # import pymel.core as pm
    # import data.utils as utils
    from .data import utils
    # reload(utils)

    if not cmds.pluginInfo('mtoa', q=1, loaded=1):
        cmds.loadPlugin('mtoa')
    cmds.setAttr('defaultRenderGlobals.currentRenderer', 'arnold', type='string')

    import maya.mel as mel

    mel.eval('''addOneTabToGlobalsWindow("arnold", "Common", "createArnoldRendererCommonGlobalsTab");''')
    mel.eval('''addOneTabToGlobalsWindow("arnold", "Arnold Renderer", "createArnoldRendererGlobalsTab");''')
    mel.eval('''addOneTabToGlobalsWindow("arnold", "System", "createArnoldRendererSystemTab");''')
    mel.eval('''addOneTabToGlobalsWindow("arnold", "AOVs", "createArnoldAOVTab");''')
    mel.eval('''addOneTabToGlobalsWindow("arnold", "Diagnostics", "createArnoldRendererDiagnosticsTab");''')
except:
    pass

# __CURRENT_PATH__ = os.path.dirname(__file__)
from . import __file__ as _initpy_file
__CURRENT_PATH__ = os.path.dirname(os.path.realpath(_initpy_file))


class ArnoldAOVsManageMain(QMainWindow):
    label = 'ArnoldAOV Manage @ Jarry'
    ver = 'v0.8'
    active_widget_class = AOVActiveItemWidget.AOVActiveItemWidget
    available_widget_class = AOVAvailableWidget.AOVAvailableWidget
    lightgroup_widget_class = AOVLightGroupWidget.AOVLightGroupWidget
    scheme = qcs.QColorScheme

    def __init__(self, parent=None, project=''):
        super(ArnoldAOVsManageMain, self).__init__(parent)
        self.setObjectName(self.label)
        self.resize(700, 600)
        self.setWindowTitle(self.label)
        # self.setStyleSheet("QWidget{font-family:Microsoft YaHei;}")
        # self.setStyleSheet(rq.RenderQss(os.path.join(__CURRENT_PATH__, r'data\MainWidget.qss')))

        mainWidget = QWidget()
        self.setCentralWidget(mainWidget)
        main_layout = QVBoxLayout()
        mainWidget.setLayout(main_layout)

        group_widget = QGroupBox()
        group_layout = QVBoxLayout()
        group_widget.setLayout(group_layout)

        # build group title button
        h_infoLayout = QHBoxLayout()
        info_label = QLabel()
        info_label.setText(u'# 选择第一列的aov，>>添加至分组的列表中,<<可退回，绿色表示文件内已经存在')
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        refresh_item_button = QPushButton(u'刷新')

        new_item_button = QPushButton(u' add new Group ')
        h_infoLayout.addWidget(info_label)
        h_infoLayout.addItem(spacerItem)
        h_infoLayout.addWidget(refresh_item_button)
        # h_infoLayout.addWidget(new_item_button)

        # build aov list
        self.aov_layout = QHBoxLayout()

        self.default_aov_layout = QVBoxLayout()

        # self.light_group_layout = QHBoxLayout()
        self.light_group_widget = self.lightgroup_widget_class()

        self.aov_item_layout = QHBoxLayout()

        self.available_aov_widget = self.available_widget_class()
        self.available_aov_widget.add_button.clicked.connect(self.add_custom_aov)
        self.default_aov_layout.addWidget(self.available_aov_widget)
        self.default_aov_layout.addWidget(self.light_group_widget)

        self.aov_layout.addLayout(self.default_aov_layout)
        self.aov_layout.addLayout(self.aov_item_layout)

        group_layout.addLayout(h_infoLayout)
        group_layout.addLayout(self.aov_layout)

        prefix_layout = QHBoxLayout()
        prefix_label = QLabel('Override Path Prefix')
        self.prefix_edit = QLineEdit('<Scene>/<RenderLayer>/<RenderLayer>_<Group>/<RenderLayer>_<Group>')
        prefix_layout.addWidget(prefix_label)
        prefix_layout.addWidget(self.prefix_edit)

        create_button = QPushButton('Add / Edit AOVs')
        create_button.setMinimumHeight(30)
        main_layout.addLayout(self.title_layout(self.label, self.ver))
        main_layout.addWidget(group_widget)
        main_layout.addLayout(prefix_layout)
        main_layout.addWidget(create_button)

        # singnal
        refresh_item_button.clicked.connect(self.refersh_list_aov)
        new_item_button.clicked.connect(self.add_new_item_widget)
        create_button.clicked.connect(self.add_aov_scence)
        # style
        scheme = self.scheme()
        scheme.setColor(QColor(80, 150, 0, 255), highlightColor=QColor(250, 250, 250), spread=5.5)
        scheme.applyStyle(create_button)
        scheme.setColor(QColor(180, 100, 0, 255), highlightColor=QColor(250, 250, 250), spread=5.5)
        scheme.applyStyle(refresh_item_button)
        self.setup_ui()

    def setup_ui(self):
        # steup default aovs
        default_aov_config = os.path.join(__CURRENT_PATH__, 'config', 'DefaultAOVs.json')
        default_aov_data = JJson(default_aov_config).read()
        self.available_aov_list = default_aov_data.get('AOVs')
        self.available_lpe_list = default_aov_data.get('LPE')
        print(self.available_lpe_list)
        lep_keys = [list(l)[0] for l in self.available_lpe_list]
        self.available_aov_list += lep_keys

        # print len(utils.getDefaultAllAOVs())
        # print len(self.available_aov_list)
        self.available_aov_widget.list_widget.addItems(self.available_aov_list)
        self.available_aov_widget.list_widget.update()
        proj_aov_config = os.path.join(__CURRENT_PATH__, 'config', 'LFC.json')
        proj_aov_data = JJson(proj_aov_config).read()
        for group_item in proj_aov_data.get('group'):
            aovs = group_item.get('AOVs')
            for aov in aovs:
                if aov not in self.available_aov_list:
                    self.available_aov_list.append(aov)
            self.add_aov_item_widget(group_item)
        # self.available_aov_list = list(set(self.available_aov_list))
        self.refersh_list_aov()

    def add_new_item_widget(self):
        result, check = QInputDialog.getText(self, 'Aov custom', u'custom name：')
        if check:
            group_item = {"name": result, "merge": True, "half": True, "group": "Color", "AOVs": []}
            self.add_aov_item_widget(group_item)

    def add_aov_item_widget(self, group_item):
        widget_class = self.active_widget_class
        widget_class.LABEL = group_item.get('name')
        aov_widget = widget_class()
        # aov_widget.setObjectName(group_item.get('name'))

        aov_widget.merge_cbx.setChecked(group_item.get('merge'))
        aov_widget.half_cbx.setChecked(group_item.get('half'))
        aov_widget.group_edit.setText(group_item.get('group'))
        aov_widget.prefix_cbx.setChecked(group_item.get('prefix'))
        aov_widget.list_widget.addItems(group_item.get('AOVs'))
        self.aov_item_layout.addWidget(aov_widget)
        aov_widget.add_button.clicked.connect(self.add_active)
        aov_widget.remove_button.clicked.connect(self.remove_active)
        aov_widget.group_button.clicked.connect(self.add_aov_group_light)

        aov_widget.list_widget.update()

    def refersh_list_aov(self):
        self.available_aov_widget.list_widget.clear()
        self.available_aov_widget.list_widget.addItems(self.available_aov_list)
        self.available_aov_widget.list_widget.update()

        # 遍历出页面中默认配置的aovs
        widget_aovs_texts = []
        for wi in range(self.aov_item_layout.count()):
            w = self.aov_item_layout.itemAt(wi).widget()
            widget_aovs_texts += w.list_widget.texts()
        # 遍历每个group,将不存在默认配置group中的aov列到对应的group下
        for wi in range(self.aov_item_layout.count()):
            w = self.aov_item_layout.itemAt(wi).widget()
            if w._label in ['Data', 'Crypto', 'Custom']:
                w.group_button.setHidden(True)
                # QPushButton.setHidden()
            _aovs = []
            # 列出对应group的drive所连接的aov
            if w._label == 'Default':
                _aovs = cmds.listConnections('defaultArnoldDriver.message', source=True, destination=1,
                                             type='aiAOV') or []
            else:
                driver_node = 'aiAOVDriver_%s' % w._label
                if cmds.objExists(driver_node):
                    _aovs = cmds.listConnections('%s.message' % driver_node, source=True, destination=1,
                                                 type='aiAOV') or []
            # 查询只要不在配置列表里，那就添加到对应的widget里去
            for a in _aovs:
                aov_name = cmds.getAttr('%s.name' % a)
                if aov_name not in widget_aovs_texts:
                    w.list_widget.addItems([aov_name])
            # 移除掉基础aov中的列表
            for item in w.list_widget.items():
                self.available_aov_widget.list_widget.takeText(item.text())
            w.list_widget.update()

    def add_custom_aov(self):
        result, check = QInputDialog.getText(self, 'Aov custom', u'custom name：')
        if check:
            self.available_aov_list.append(result)
            self.refersh_list_aov()

    def add_active(self):
        texts = self.available_aov_widget.list_widget.selected_texts()
        w = self.sender().parent()
        w.list_widget.addItems(texts)
        w.list_widget.update()
        # w.list_widget.set_select_texts(texts)
        self.refersh_list_aov()
        # QListWidgetItem

    def remove_active(self):
        w = self.sender().parent()
        texts = w.list_widget.selected_texts()
        for text in texts:
            w.list_widget.takeText(text)
        self.refersh_list_aov()

    def add_aov_group_light(self):
        pass
        light_group_w = self.light_group_widget.list_widget
        light_group_sl = light_group_w.selected_texts()
        aov_group_w = self.sender().parent().list_widget
        aov_group_sl = aov_group_w.selected_texts()
        if light_group_sl and aov_group_sl:
            for lg in light_group_sl:
                if lg == 'default':
                    continue
                for aov in aov_group_sl:
                    aov_node = 'aiAOV_%s' % aov
                    if cmds.objExists(aov_node):
                        aov_add_lg_node = '%s_%s' % (aov, lg)
                        if aov_add_lg_node not in aov_group_w.texts():
                            aov_group_w.addItem(aov_add_lg_node)
                    aov_group_w.update()

    def add_aov_scence(self):
        for wi in range(self.aov_item_layout.count()):
            w = self.aov_item_layout.itemAt(wi).widget()
            # w_items = w.list_widget.items()
            texts = w.list_widget.texts()

            group = w.group_edit.text()
            # w._label = group
            label = w._label
            data_aovs = texts

            prefix = ''
            if w.prefix_cbx.isChecked():
                prefix = self.prefix_edit.text()
                #prefix = '<Scene>/<RenderLayer>/<RenderLayer>_<Group>/<RenderLayer>_<Group>'
                prefix = prefix.replace('<Group>', group)
            else:
                prefix = ''

            utils.createAOVs(data_aovs, label, prefix, w.half_cbx.isChecked(), w.merge_cbx.isChecked(), self.available_lpe_list)

            list_connect_aov = cmds.listConnections('defaultArnoldRenderOptions.aovList') or []
            aov_list_num = len(list_connect_aov)

            for aov in data_aovs:
                aov_node_name = 'aiAOV_' + aov
                if not cmds.objExists(aov_node_name):
                    continue

                if aov_node_name not in list_connect_aov:
                    # print aov_node_name
                    cmds.connectAttr(aov_node_name + '.message', 'defaultArnoldRenderOptions.aovList[%s]' % str(aov_list_num))
                    aov_list_num += 1

                item = w.list_widget.item_from_text(aov)
                if item.checkState():
                    cmds.setAttr('%s.enabled' % aov_node_name, 1)
                else:
                    cmds.setAttr('%s.enabled' % aov_node_name, 0)

        # cmds.setAttr("defaultRenderGlobals.imageFilePrefix", "<Scene>/<RenderLayer>/<RenderLayer>", type="string")
        # cmds.setAttr("defaultArnoldDriver.defaultArnoldDriver", "exr", type="string")
        # cmds.setAttr("defaultRenderGlobals.extensionPadding", 4)
        self.refersh_list_aov()

    def createConfigContextMenu(self):
        '''''
        '''
        # 创建QMenu
        self.contextMenu = QMenu(self)
        config_file_list = os.listdir(os.path.join(__CURRENT_PATH__, 'config'))
        for f in config_file_list:
            if not f.endswith('json'):
                break
            action = QAction(self)
            action.setText('%s' % os.path.basename(f).split('.')[0])
            action.triggered.connect(self.load_config)
            self.contextMenu.addAction(action)
        # self.action_exit.triggered.connect(self.destroy)
        self.config_button.setMenu(self.contextMenu)

    def load_config(self):
        action = self.sender()
        name = action.text()
        self.loadconfig(name)

    def loadconfig(self, project='YCM'):
        self.project = project
        self.setWindowTitle('%s - <%s>' % (self.label, project))

    def title_layout(self, title='', ver=''):
        self.title_HLayout = QHBoxLayout()
        self.title_HLayout.setObjectName("title_HLayout")
        self.line_r = QFrame()
        self.line_r.setMaximumSize(QSize(2, 20))
        self.line_r.setStyleSheet("background-color: rgb(255, 0, 0);")
        self.line_r.setFrameShadow(QFrame.Sunken)
        self.line_r.setLineWidth(1)
        self.line_r.setMidLineWidth(0)
        self.line_r.setFrameShape(QFrame.VLine)
        self.line_r.setFrameShadow(QFrame.Sunken)
        self.line_r.setObjectName("line_r")
        self.title_HLayout.addWidget(self.line_r)
        self.line_g = QFrame()
        self.line_g.setMaximumSize(QSize(2, 20))
        self.line_g.setStyleSheet("background-color: rgb(0, 255, 0);")
        self.line_g.setFrameShape(QFrame.VLine)
        self.line_g.setFrameShadow(QFrame.Sunken)
        self.line_g.setObjectName("line_g")
        self.title_HLayout.addWidget(self.line_g)
        self.line_b = QFrame()
        self.line_b.setMaximumSize(QSize(2, 20))
        self.line_b.setStyleSheet("background-color: rgb(0, 85, 255);")
        self.line_b.setLineWidth(1)
        self.line_b.setFrameShape(QFrame.VLine)
        self.line_b.setFrameShadow(QFrame.Sunken)
        self.line_b.setObjectName("line_b")
        self.title_HLayout.addWidget(self.line_b)
        self.titleIconLab = QLabel()
        self.titleIconLab.setText("")
        self.titleIconLab.setObjectName("titleIconLab")
        self.title_HLayout.addWidget(self.titleIconLab)
        self.titleLab = QLabel()
        self.titleLab.setText(title)
        self.titleLab.setMaximumSize(QSize(16777215, 25))
        self.titleLab.setStyleSheet(u"QLabel#titleLab {\n"
                                    u"    font: 10pt \"隶书\";\n"
                                    u"    color: rgb(0, 131, 200); \n"
                                    u"    padding: 3px;\n"
                                    u"}")
        self.titleLab.setFont(QFont(u'隶书'))
        self.titleLab.setObjectName("titleLab")
        self.title_HLayout.addWidget(self.titleLab)
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.title_HLayout.addItem(spacerItem)
        self.titleLab_ver = QLabel()
        self.titleLab_ver.setText(ver)
        self.titleLab_ver.setMaximumSize(QSize(16777215, 25))
        self.titleLab_ver.setStyleSheet(u"QLabel {\n"
                                        u"    font: 9pt \"隶书\";\n"
                                        u"    color: rgb(200, 100, 0); \n"
                                        u"    padding: 3px;\n"
                                        u"}")
        self.titleLab_ver.setObjectName("titleLab_ver")
        self.title_HLayout.addWidget(self.titleLab_ver)
        self.title_tb = QToolButton()
        self.title_tb.setObjectName("title_tb")
        self.title_tb.setHidden(True)
        self.title_HLayout.addWidget(self.title_tb)
        return self.title_HLayout


def run(project='TJ'):
    # import pymel.core as pm
    # import widget.getMayaWindow as gmw
    from .widget import getMayaWindow as gmw
    name = ArnoldAOVsManageMain.label
    if cmds.window(name, q=1, ex=1):
        cmds.deleteUI(name)
    ui = ArnoldAOVsManageMain(parent=gmw.getMayaWindow(), project=project)
    # ui.loadconfig(project)
    ui.show()


if __name__ == "__main__":
    app = QApplication()
    my_ui = ArnoldAOVsManageMain()
    my_ui.show()
    app.exec_()
